package com.freeman.boot.auth;

import com.alibaba.fastjson.JSON;
import com.freeman.boot.utils.Sign;
import com.freeman.boot.utils.WebHttpClientUtils;
import com.freeman.boot.wechat.Ticket;
import com.freeman.boot.wechat.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class WeChatServiceImpl implements WeChatService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${app.wx.appID}")
    private String appID;

    @Value("${app.wx.appSecret}")
    private String appsecret;
    @Value("${app.wx.appTokenKey}")
    private String appTokenKey;
    @Value("${app.wx.appTicketKey}")
    private String appTicketKey;

    @Override
    public Map<String, String> getWeChatJsConfig(String url) {
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        String jsTicket = opsForValue.get(appTicketKey);
        if (StringUtils.isEmpty(jsTicket)) {
            String accessToken = opsForValue.get(appTokenKey);
            if (StringUtils.isEmpty(accessToken)) {
                Token token = requestToken(appID, appsecret);
                accessToken = token.getAccess_token();
                opsForValue.set(appTokenKey, accessToken, token.getExpires_in(), TimeUnit.SECONDS);
            }
            Ticket ticket = requestTicket(accessToken);
            jsTicket = ticket.getTicket();
            opsForValue.set(appTicketKey, jsTicket, ticket.getExpires_in(), TimeUnit.SECONDS);
        }
        Map<String, String> sign = Sign.sign(jsTicket, url);
        sign.put("appId", appID);
        return sign;
    }

    private static Token requestToken(String appID, String appsecret) {
        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appID + "&secret=" + appsecret;
        String tokenResult = WebHttpClientUtils.get(tokenUrl);
        return JSON.parseObject(tokenResult, Token.class);
    }


    private static Ticket requestTicket(String accessToken) {
        String ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
        String ticketResult = WebHttpClientUtils.get(ticketUrl);
        return JSON.parseObject(ticketResult, Ticket.class);
    }
}